﻿using System;
using System.Linq;

namespace Cluster
{
    public abstract partial class ClusterManager
    {
        private bool isLeader;

        protected virtual void TakeLeadership()
        {
            Info("Elected to leader");
        }

        /// <summary>
        /// Choses the leader in the cluster.
        /// The leader is the oldest (smallest id) node.
        /// </summary>
        private void ChoseLeader()
        {
            if (GetLeader() == SelfNode.ZkPath && isLeader == false)
            {
                isLeader = true;

                try
                {
                    // we are the chosen ones
                    // but with great power comes great responsibility
                    TakeLeadership();
                }
                catch (Exception e)
                {
                    WarnEx("Failed to take leadership", e);
                }
            }
        }

        /// <summary>
        /// Retrieves the node with the least id
        /// </summary>
        /// <returns></returns>
        private string GetLeader()
        {
            return ClusterView.Min(cn => cn.ZkPath);
        }
    }
}
